package com.tdkj.service.shop.impl;

import java.sql.Timestamp;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Component;

import com.tdkj.dao.shop.IBeanGoodShowcaseCustomBuyDao;
import com.tdkj.model.shop.BeanGoodShowcase;
import com.tdkj.model.shop.BeanGoodShowcaseCustom;
import com.tdkj.model.shop.BeanGoodShowcaseCustomBuy;
import com.tdkj.model.user.BeanUser;
import com.tdkj.service.BaseService;
import com.tdkj.service.ServiceException;
import com.tdkj.service.financial.IBeanConsumeRecordService;
import com.tdkj.service.shop.IBeanGoodShowcaseCustomBuyService;

@Component
public class BeanGoodShowcaseCustomBuyServiceImpl extends BaseService implements
		IBeanGoodShowcaseCustomBuyService {
	
	private IBeanConsumeRecordService consumeRecordService;
	
	@Resource
	public void setConsumeRecordService(
			IBeanConsumeRecordService consumeRecordService) {
		this.consumeRecordService = consumeRecordService;
	}

	private IBeanGoodShowcaseCustomBuyDao beanGoodShowcaseCustomBuyDao;
	
	@Resource
	public void setBeanGoodShowcaseCustomBuyDao(
			IBeanGoodShowcaseCustomBuyDao beanGoodShowcaseCustomBuyDao) {
		this.beanGoodShowcaseCustomBuyDao = beanGoodShowcaseCustomBuyDao;
	}
	
	@Override
	public BeanGoodShowcaseCustomBuy addBuy(Long userId, Long customId) throws ServiceException {
		BeanUser user = beanGoodShowcaseCustomBuyDao.findById(userId, BeanUser.class);
		BeanGoodShowcaseCustom custom = beanGoodShowcaseCustomBuyDao.findById(customId, BeanGoodShowcaseCustom.class);
		
		BeanGoodShowcaseCustomBuy bean = null;
		bean = new BeanGoodShowcaseCustomBuy();
		bean.setUser(user);
		bean.setCustom(custom);
		bean.setBuyTime(new Timestamp(System.currentTimeMillis()));
		beanGoodShowcaseCustomBuyDao.save(bean);
		
		BeanGoodShowcase showcase = user.getShop().getShowcase();
		if(showcase.getQuantity() == null){
			showcase.setQuantity(0);
		}
		showcase.setQuantity(showcase.getQuantity() + custom.getQuantity());
		
		int price = custom.getPrice().intValue();
		consumeRecordService.create(userId, price, custom.getUnit(), bean.getId(), BeanGoodShowcaseCustomBuy.class, "橱窗购买");
		
		return bean;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<BeanGoodShowcaseCustomBuy> getBuyLogs(Long userId) {
		BeanUser user = beanGoodShowcaseCustomBuyDao.findById(userId, BeanUser.class);
		List<BeanGoodShowcaseCustomBuy> logs = beanGoodShowcaseCustomBuyDao.getSession().createCriteria(BeanGoodShowcaseCustomBuy.class).add(Restrictions.eq("user", user)).addOrder(Order.desc("buyTime")).list();
		return logs;
	}

}
